import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:village_android/common/NoKeyboardEditableTextFocusNode.dart';
import 'package:village_android/component/images_collection.dart';
import 'package:village_android/component/jd_button.dart';
import 'package:village_android/config/service_method.dart';
import 'package:village_android/main.dart';
import 'package:village_android/model/charge_model.dart';
import 'package:village_android/model/dept_model.dart';
import 'package:village_android/model/menu_model.dart';
import 'package:village_android/model/sys_config_model.dart';
import 'package:village_android/model/user_model.dart';
import 'package:village_android/pages/auth/register_first_page.dart';
import 'package:village_android/pages/user/user_list.dart';
import 'package:village_android/utils/common_utils.dart';
import 'package:village_android/utils/http_utlis.dart';
import 'package:village_android/utils/store_utils.dart';
import 'dart:convert' as convert;
import 'package:quiver/strings.dart';

class ChargeSubmitPage extends StatefulWidget {

  List<SysConfigModel> sysConfigList = [];
  ChargeModel chargeModel;
  MenuModel menuModel;

  ChargeSubmitPage({this.chargeModel,this.menuModel});

  @override
  _ChargeSubmitPageState createState() => new _ChargeSubmitPageState();
}

class _ChargeSubmitPageState extends State<ChargeSubmitPage> {
  final _formKey = GlobalKey<FormState>();

  String _title;
  String _username;
  String _userphone;
  String _address;
  String _content;
  String _type;
  String _typeName;
  String _medias = "";

  bool isEdit = false;

  @override
  void initState() {
    super.initState();

    widget.sysConfigList
        .add(SysConfigModel(code: "2001", name: "村情民意", value: "1"));
    widget.sysConfigList
        .add(SysConfigModel(code: "2002", name: "调查征集", value: "2"));
    widget.sysConfigList
        .add(SysConfigModel(code: "2003", name: "投诉建议", value: "3"));

    if(widget.chargeModel==null) {
      widget.chargeModel = new ChargeModel();
    }else {
      isEdit = true;
    }
    _title = widget.chargeModel.title;
    _username = widget.chargeModel.userName;
    _userphone = widget.chargeModel.userPhone;
    _content = widget.chargeModel.content;
    _address = widget.chargeModel.address;
    _type = widget.chargeModel.type.toString();

    if(_type == "1") {
      _typeName = "村情民意";
    }else if(_type == "2") {
      _typeName = "调查征集";
    }else if(_type == "3") {
      _typeName = "投诉建议";
    }
    _medias = widget.chargeModel.medias;

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("提交" + (widget.menuModel!=null ? widget.menuModel.title : '投诉/建议')),
      ),
      body: localWidget(),
      bottomNavigationBar: isEdit == true ? null :initBottom(),
    );
  }

  Widget localWidget() {
    return Container(
      padding: EdgeInsets.all(20),
      child: Form(
        key: _formKey,
        child: ListView(
          children: <Widget>[
            initChargeTitle(),
            initUserName(),
            initUserPhone(),
            initAddress(),
            initType(),
            initContent(),
            SizedBox(height: 10.0),
            Text(
              isEdit == true ? "图片" :"上传图片",
              style: TextStyle(color: Colors.red),
            ),
            SizedBox(height: 10.0),
            initMutilImages(),
            SizedBox(height: 2.0),
            SizedBox(height: 100.0),
          ],
        ),
      ),
    );
  }

  Widget networkWidget() {
    return null;
  }

  Padding initTitle() {
    return Padding(
      padding: EdgeInsets.all(10),
      child: Text(
        '阳光北亭-注册',
        style: TextStyle(
            fontSize: 30.0,
            color: Colors.deepOrange,
            fontWeight: FontWeight.bold),
        textAlign: TextAlign.center,
      ),
    );
  }

  TextFormField initChargeTitle() {
    return TextFormField(
      enabled: !isEdit,
      initialValue: _title,
      onSaved: (String value) => _title = value,
//      maxLength: 11,
      decoration: InputDecoration(labelText: '事由标题', hintText: "请输入事项原由"),
    );
  }


  TextField initUserName() {

    return TextField(
      enabled: !isEdit,
      controller: TextEditingController()
        ..text = _username,
      focusNode: NoKeyboardEditableTextFocusNode(),
      onTap: (() async {

        var page = UserListPage(deptId: 25,);
        var result = await Navigator.push(context, new MaterialPageRoute(builder: (context) => page));
        if(result!=null){
          UserModel user = result as UserModel;
          setState(() {
            _username = user.account + '-' + user.name ;
          });
        }
      }),
      decoration: new InputDecoration(labelText: '投诉/建议人'),
      onChanged: (value) {},
    );

  }

  TextFormField initUserPhone() {
    return TextFormField(
      enabled: !isEdit,
      initialValue: _userphone,
      onSaved: (String value) => _userphone = value,
      decoration: InputDecoration(labelText: '联系电话'),
    );
  }

  TextFormField initAddress() {
    return TextFormField(
      enabled: !isEdit,
      initialValue: _address,
      onSaved: (String value) => _address = value,
      decoration: InputDecoration(labelText: '事项地址'),
    );
  }

  TextField initType() {
    return TextField(
      enabled: !isEdit,
      controller: TextEditingController()..text = _typeName,
      focusNode: NoKeyboardEditableTextFocusNode(),
      onTap: (() {
        showConfigAlertDialog();
      }),
      decoration: new InputDecoration(labelText: '类别', hintText: '点击选择'),
      onChanged: (value) {
        _type = value;
      },
    );
  }

  TextFormField initContent() {
    return TextFormField(
      enabled: !isEdit,
      initialValue: _content,
      onSaved: (String value) => _content = value,
      decoration: InputDecoration(labelText: '事项描述'),
    );
  }

  Widget initMutilImages() {
    List items = [];
    if (!isEmpty(_medias)) {
       items=_medias.split(",");
    }
    return ImagesCollectionPage(
      items: items,
      itemsCallBack: ((items) {
        List medias = items as List;
        String mediasString = "";
        for (var i = 0; i < medias.length; i++) {
          if (i > 0) {
            mediasString = mediasString +
                (mediasString.length == 0 ? "" : ",") +
                medias[i];
          }
        }
        _medias = mediasString;
        print(_medias);
      }),
    );
  }

  Widget initBottom() {
    return BottomAppBar(
        child: Row(
      children: <Widget>[
        Expanded(
            child: JdButton(
          callBack: () {
            //CommonUtils.showToast(context, '登录');
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              showAlertDialog();
            }
          },
          text: "提交",
          color: Colors.red,
        )),
      ],
    ));
  }



  List<Widget> getRadioList() {
    List<RadioListTile<SysConfigModel>> radioList = [];
    for (int i = 0; i < widget.sysConfigList.length; i++) {
      SysConfigModel item = widget.sysConfigList[i];
      RadioListTile listTile = RadioListTile<SysConfigModel>(
        value: item,
        title: Text(item.name),
        groupValue: null,
        onChanged: (value) {
          setState(() {
            _type = value.value.toString();
            _typeName = value.name;
          });
//          _deptId = value;

          Navigator.of(context).pop();
        },
      );
      radioList.add(listTile);
    }
    return radioList;
  }

  void showConfigAlertDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return new SimpleDialog(
          title: new Text('选择类别'),
          children: getRadioList(),
        );
      },
    ).then((val) {});
  }

  void showAlertDialog() {
    if (isEmpty(_userphone)) {
      CommonUtils.showToast(context, "请填写手机");
      return;
    }
    if (isEmpty(_username)) {
      CommonUtils.showToast(context, "请填写投诉人名字");
      return;
    }
    if (isEmpty(_title)) {
      CommonUtils.showToast(context, "请填写标题");
      return;
    }
    if (isEmpty(_content)) {
      CommonUtils.showToast(context, "请填写事项描述");
      return;
    }
    if (isEmpty(_type)) {
      CommonUtils.showToast(context, "请选择类别");
      return;
    }

    showDialog(
        context: context,
        builder: (_) => new AlertDialog(
                title: new Text("是否提交"),
                content: new Text(""),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text("取消"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      toDone();
                    },
                  )
                ]));
  }

  Future toDone() async {
    FormData formData = new FormData.from({
      "title": _title,
      "userPhone": _userphone,
      "userName": _username,
      "address": _address,
      "content": _content,
      "type": _type,
      "medias": _medias,
    });
//    var dio = new Dio();
//    var response =
//        await dio.post(BaseUrl.url + "/mgr/register", data: formData);
//    print(response.data.toString());
//
//    var data = response.data;

    HttpUtils.postForm("/api/charge/addItem", formData: formData, success: (data) {
      CommonUtils.showToast(context, "增加成功");
      Navigator.of(context).pop("confirm");
    }, error: (errorMsg) {
      CommonUtils.showToast(context, errorMsg);
    });
  }
}
